<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Poruke
 *
 * dz5_poruke contains id, idUsername, naslov, sadrzaj, vrijeme
 * Methods: add, delete, calculatePages, getAll, getOnePage
 *
 * @author mateo
 */
class MessageRepository {

    public function addMessage($db, $message) {
        $dodajPoruku = $db->prepare("INSERT INTO Message(`UserID`,`Time` ,`Comment`, `PictureID`,`MIMEType`, `Latitude`, `Longitude`) VALUES(?, NOW(), ?, ?, ?, ?, ?)");
        $dodajPoruku->execute(array(
            $message->getUserId(),
            $message->getComment(),
            $message->getPictureId(),
            $message->getMIMEType(),
            $message->getLatitude(),
            $message->getLongitude()));
    }

    public function addCommentToMessage($db, $messageId, $userId, $text){
      $addMessage = $db->prepare("INSERT INTO Comment(`messageID`,`userID` ,`text`, `time`) VALUES(?, ?, ?, NOW())");
      $addMessage->execute(array(
          $messageId,
          $userId,
          $text
      ));
      return $db->lastInsertId();
    }
    
    public function deleteComment($db, $id){
        $message = $db->prepare("DELETE FROM Comment WHERE ID = ?");
        $message->execute(array($id));
    }
    
    public function getMessage($db, $id) {
        $message = $db->prepare("SELECT * FROM Message WHERE ID = ?");
        $message->execute(array($id));
        return MessageRepository::htmlSpecialCharactersField($message->fetchAll());
    }

    public function deleteMessage($db, $id) {
        $messageToDelete = $this->getMessage($db, $id);        
        $this->deleteImage($messageToDelete[0]['PictureID']);
        $message = $db->prepare("DELETE FROM Message WHERE ID = ?");
        $message->execute(array($id));
    }

    public function getAllMessages($db) {
        $messages = $db->prepare(" select Message.ID, Message.UserID, Comment, 
            Username, PictureID,Message.Time, MIMEType,Latitude,Longitude from Message join User on Message.UserID = User.ID 
            order by Message.Time DESC;");
        $messages->execute();
        return MessageRepository::htmlSpecialCharactersField($messages->fetchAll());
    }

    public function findMessage($db, $comment) {
        $search = $db->prepare("SELECT * FROM Message WHERE Comment = ?");
        $search->execute(array($comment));
        return MessageRepository::htmlSpecialCharactersField($search->fetchAll());
    }

    public function getPage($db, $pageNumber) {
        $messages = new MessageRepository();
        $allMessages = $messages->getAllMessages($db);
        $numberOfAdded = 0;
        $newMessages[0] = 0;
        for ($i = $pageNumber * 10 - 10; $i < count($allMessages); $i+=1) {
            $newMessages[$numberOfAdded] = $allMessages[$i];

            if ($numberOfAdded == 9) {
                break;
            }
            $numberOfAdded += 1;
        }
        return $newMessages;
    }

    public function calculateNumberOfPages($db) {
        $messages = new MessageRepository();
        $allMessages = $messages->getAllMessages($db);
        return ceil(count($allMessages) / 10);
    }
    
    public function getCommentsForMessage($db, $id){
        $message = $db->prepare("SELECT * FROM Message, Comment, User WHERE Message.ID = ? &&
            Comment.MessageID = ? && User.ID = Comment.userID");
        $message->execute(array($id,$id));
        return ($message->fetchAll());
    }

    private static function htmlSpecialCharactersField($field) {
        foreach ($field as $outerKey => $entity) {
            foreach ($entity as $innerKey => $value) {
                //html tagovi dopusteni u sadrzaju
                if ($innerKey != 'PictureID') {
                    $newField[$outerKey][$innerKey] = htmlspecialchars($value);
                } else {
                    $newField[$outerKey][$innerKey] = $value;
                }
            }
        }
        if (isset($newField)) {
            return $newField;
        } else {
            return $newField = array();
        }
    }
    
    private function deleteImage($imageName){
        if (file_exists('pictures/'.$imageName) && file_exists('thumbs/'.$filename)) {
            unilnk('pictures/'.$imageName);
            unilnk('thumbs/'.$imageName);
        }
    }

}
?>
